package com.leon.registerclient;

import java.util.UUID;

public class RegisterClient {
    public static final String SERVICE_NAME = "inventory-service";

    /**
     * 服务实例id
     */
    private String serviceInstanceId;

    private HttpSender httpSender;

    private HeartBeatThread heartBeatThread;

    private volatile boolean isRunning;

    public RegisterClient() {
        this.httpSender = new HttpSender();
        this.serviceInstanceId = UUID.randomUUID().toString().replace("-", "");
        this.heartBeatThread = new HeartBeatThread();
    }

    public void shutdown() {
        this.isRunning = false;
        this.heartBeatThread.interrupt();
        this.httpSender.cancel(SERVICE_NAME, serviceInstanceId);
    }

    public void start() throws InterruptedException {
        RegisterWorker registerWorker = new RegisterWorker(serviceInstanceId);
        registerWorker.start();
        registerWorker.join();
        this.heartBeatThread.start();
    }

    private class HeartBeatThread extends Thread {


        @Override
        public void run() {
            HeartbeatRequest heartbeatRequest = new HeartbeatRequest();
            heartbeatRequest.setServiceInstanceId(serviceInstanceId);
            HeartbeatResponse heartbeatResponse = null;

            while (isRunning) {
                try {
                    heartbeatResponse = httpSender.heartbeat(heartbeatRequest);
                    System.out.println("心跳的结果为：" + heartbeatResponse.getStatus() + "......");
                    Thread.sleep(30 * 1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public Boolean isRunning() {
        return this.isRunning;
    }
}
